/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package presentacion;

import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import logica.ControladorArticulos;

/**
 *
 * @author Andres
 */
public class MoverStockProducto extends AZPanel {

    private ControladorArticulos articulos;

    @Override
    protected void cargarCaracteristicas() {
        cargarCombo("locales", this.jComboBox1);
        cargarCombo("locales", this.jComboBox2);
        cargarCombo("descripciones", this.jComboBox3);
    }

    public ControladorArticulos getArticulos() {
        return articulos;
    }

    public void setArticulos(ControladorArticulos articulos) {
        this.articulos = articulos;
    }

    /**
     * Creates new form MoverStock
     */
    public MoverStockProducto() {
        initComponents();
    }

    private void cargarTabla() {
        String p = this.jTextField1.getText();
        if (p.equals("")) {
            return;
        }
        String de = this.jComboBox1.getSelectedItem().toString();
        if (de.equals("")) {
            return;
        }
        String[][] aux = articulos.consultar(p, "", "", de, "", "", "", "");
        DefaultTableModel model = (DefaultTableModel) this.jTable3.getModel();
        while (model.getRowCount() != 0) {
            model.removeRow(0);
        }
        for (int i = 0; i < aux.length; i++) {
            if (!(aux[i][3].equals("*") && aux[i][4].equals("*"))) {
                model.addRow(new String[]{aux[i][3], aux[i][4], aux[i][6]});
            }
        }

        TableRowSorter rs = new TableRowSorter<DefaultTableModel>(model);
        rs.setComparator(0, comparador_talles);
        rs.setComparator(2, comparador_numerico);
        this.jTable3.setRowSorter(rs);
        this.jTable3.getRowSorter().toggleSortOrder(1);
        this.jTable3.getRowSorter().toggleSortOrder(0);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jComboBox2 = new javax.swing.JComboBox();
        jScrollPane7 = new javax.swing.JScrollPane();
        jTable3 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jComboBox3 = new javax.swing.JComboBox();
        jTextField1 = new javax.swing.JTextField();

        setMinimumSize(new java.awt.Dimension(975, 528));

        jLabel2.setText("De:");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBox1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox1ItemStateChanged(evt);
            }
        });

        jLabel3.setText("a:");

        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jTable3.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Talle", "Color", "Cantidad"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane7.setViewportView(jTable3);

        jButton1.setText("Mover stock");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N

        jLabel4.setText("Codigo");

        jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBox3.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox3ItemStateChanged(evt);
            }
        });

        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField1KeyReleased(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane7, javax.swing.GroupLayout.DEFAULT_SIZE, 705, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1)))
                .addContainerGap(260, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(51, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.jLabel1.setText("");
        String p = this.jComboBox3.getSelectedItem().toString();
        if (p.equals("")) {
            this.jLabel1.setText("Ingrese Codigo");
            return;
        }
        String de = this.jComboBox1.getSelectedItem().toString();
        if (de.equals("")) {
            this.jLabel1.setText("Ingrese De");
            return;
        }
        String a = this.jComboBox2.getSelectedItem().toString();
        if (a.equals("")) {
            this.jLabel1.setText("Ingrese A");
            return;
        }

        TableModel tabla = this.jTable3.getModel();
        ArrayList<String[]> lineas = new ArrayList<String[]>();
        String t, c, cant;
        for (int i = 0; i < tabla.getRowCount(); i++) {
            t = tabla.getValueAt(i, 0).toString();
            c = tabla.getValueAt(i, 1).toString();
            if(tabla.getValueAt(i, 2) != null){
                cant = tabla.getValueAt(i, 2).toString();
            } else {
                cant = "0";
            }
            if (!t.equals("") && !c.equals("") && !cant.equals("0")) {
                lineas.add(new String[]{t, c, cant});
            } else {
                if (!cant.equals("0")) {
                    this.jLabel1.setText("La linea " + (i + 1) + " tiene campos en blanco.");
                    return;
                }
            }
        }
        boolean resultado_de = false;
        boolean resultado_a = false;
        int i;
        for (i = 0; i < lineas.size(); i++) {
            t = lineas.get(i)[0];
            c = lineas.get(i)[1];
            cant = lineas.get(i)[2];
            resultado_de = this.articulos.actualizarStock(p, t, c, de, -Integer.parseInt(cant));
            if (!resultado_de) {
                break;
            }
            resultado_a = this.articulos.actualizarStock(p, t, c, a, Integer.parseInt(cant));
            if (!resultado_a) {
                break;
            }
        }
        if (i != lineas.size()) {
            // Si ocurrió un error revierto los cambios
            for (int j = 0; j < i; j++) {
                t = lineas.get(j)[0];
                c = lineas.get(j)[1];
                cant = lineas.get(j)[2];
                this.articulos.actualizarStock(p, t, c, de, Integer.parseInt(cant));
                this.articulos.actualizarStock(p, t, c, a, -Integer.parseInt(cant));
            }
            // Revierto la ultima transaccion considerando que haya fallado en la mitad
            t = lineas.get(i)[0];
            c = lineas.get(i)[1];
            cant = lineas.get(i)[2];
            if (!resultado_de) {
                this.articulos.actualizarStock(p, t, c, de, Integer.parseInt(cant));
            }
            if (!resultado_a) {
                this.articulos.actualizarStock(p, t, c, a, -Integer.parseInt(cant));
            }
            this.jLabel1.setText("Ocurrio un error.");
            return;
        }
        this.jLabel1.setText("Opercación exitosa");
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jComboBox3ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox3ItemStateChanged
        this.jTextField1.setText(this.jComboBox3.getSelectedItem().toString());
        cargarTabla();
    }//GEN-LAST:event_jComboBox3ItemStateChanged

    private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox1ItemStateChanged
        cargarTabla();
    }//GEN-LAST:event_jComboBox1ItemStateChanged

    private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyReleased
        String codigo = this.jTextField1.getText();
        if (codigo.length() >= 5) {
            codigo = codigo.substring(0, 5);
            this.jTextField1.setText(codigo);
            cargarTabla();
        }
    }//GEN-LAST:event_jTextField1KeyReleased
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JComboBox jComboBox3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane7;
    private javax.swing.JTable jTable3;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
